<template>
    <div class="login">
        <div class="top">
            <img alt="logo" :src="$getImageUrl(logoUrl)">
        </div>
        <div class="login-bg" :style="{'background-image': `url(${$getImageUrl(bgUrl)})`}">
            <div class="login-container">
                <div class="login-container-layout">
                    <div class="login-type">
                        <div class="login-type-name">{{loginTypes[loginType]}}</div>
                    </div>
                    <div id="login-by-disabled" v-if="loginType === 'disabled'">
                        <el-form :model="info" :rules="rules" label-position="left" label-width="0px" ref="form">
                            <el-form-item style="width:100%;">
                                浏览器已禁用cookie，请在浏览器设置中启用cookie后刷新本页面重新尝试登录。
                            </el-form-item>
                        </el-form>
                    </div>
                    <div id="login-by-username" v-if="loginType === 'username'">
                        <el-form :model="info" :rules="rules" label-position="left" label-width="0px" ref="form">
                            <el-form-item class="mb22" prop="username">
                                <el-input @change="changeUsername" auto-complete="off" class="input"
                                          placeholder="用户名/邮箱/电话号码"
                                          type="text" v-model.trim="info.username"/>
                            </el-form-item>
                            <el-form-item class="mb22" prop="password">
                                <el-input auto-complete="off" class="input" placeholder="请输入密码" type="password"
                                          v-model.trim="info.password"/>
                            </el-form-item>
                            <el-form-item class="mb22" prop="otp" v-if="need2fa">
                                <el-input auto-complete="off" class="input" placeholder="请输入动态密码" type="text"
                                          v-model.trim="info.otp"/>
                            </el-form-item>
                            <el-form-item style="width:100%;">
                                <el-button :loading="logging" @click.native.prevent="passwordSubmit" class="btn"
                                           style="width:100%;" type="primary">登录
                                </el-button>
                            </el-form-item>
                        </el-form>
                    </div>
                </div>
                <div class="oauth-box" v-if="enableOauth">
                    <div class="oauth-title">其他登录方式</div>
                    <a @click="scanLogin('WorkWeixin', wxCpAgentId)" class="oauth-type oauth-wxCp"
                       v-if="wxCpAgentId"/>
                </div>
            </div>
        </div>
    </div>
</template>
<script lang="ts">
  import ControlPanelApi from '@/api/user/controlPanelApi';
  import LoginResponse from '@/structure/loginResponse';
  import {LoginInfo, LoginType} from '@/structure/loginType';
  import Menu from '@/structure/menu';
  import User from '@/structure/user';
  import MenuUtil from '@/utils/menu';
  import UserUtil from '@/utils/user';
  import {ElForm} from 'element-ui/types/form';
  import {Component, Vue} from 'vue-property-decorator';
  import {RouteConfig} from 'vue-router';

  @Component
  export default class Page extends Vue {
    public logoUrl: string = '';
    public bgUrl: string = '';
    public need2fa: boolean = false;
    public routers: RouteConfig[] = [];
    public logging: boolean = false;
    public loginType: LoginType = 'username';
    public loginTypes: { [key: string]: string } = {
      disabled: '请启用cookie',
      username: '密码登录'
    };
    public info: LoginInfo = {
      username: '',
      password: '',
      otp: ''
    };
    public rules: any = {
      username: [
        {
          required: true,
          message: '请输入用户名'
        }
      ],
      password: [
        {
          required: true,
          message: '请输入密码'
        }
      ],
      otp: [
        {
          required: false,
          message: '请输入动态密码'
        }
      ]
    };
    public wxCpAgentId: string = '';

    public get enableOauth(): boolean {
      return !!this.wxCpAgentId;
    }

    public created() {
      this.logoUrl = process.env.VUE_APP_LOGIN_PAGE_LOGO;
      this.bgUrl = process.env.VUE_APP_LOGIN_PAGE_BG;
      this.wxCpAgentId = process.env.VUE_APP_WORK_WEIXIN_SCAN_LOGIN_AGENT_ID;
      if (!navigator.cookieEnabled) {
        this.loginType = 'disabled';
      } else if (UserUtil.getAccessToken() != null) {
        this.loadMenu();
      }
    }

    public changeUsername() {
      this.need2fa = false;
      (this.rules.otp as any)[0].required = false;
    }

    public refreshMenus(menus: Menu[]): void {
      MenuUtil.set(menus);
      MenuUtil.format(this.routers, menus);
    }

    public passwordSubmit(): void {
      (this.$refs.form as ElForm).validate((valid) => {
        if (!valid) {
          return;
        }

        const emailReg = new RegExp('^[\\.a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\\.[a-zA-Z0-9_-]+)+$');
        const phoneReg = new RegExp('^(\\(\\d{3,4}\\)|\\d{3,4}-|\\s)?\\d{7,14}$');

        const username = this.info.username;
        this.logging = true;

        if (emailReg.test(username)) {
          this.toLogin(ControlPanelApi.loginByEmail);
        } else if (phoneReg.test(username)) {
          this.toLogin(ControlPanelApi.loginByPhone);
        } else {
          this.toLogin(ControlPanelApi.login);
        }
      });
    }

    public toLogin(func: (arg: LoginInfo) => Promise<LoginResponse<User>>): void {
      func.call(ControlPanelApi, this.info)
        .then((userData) => this.login0(userData))
        .catch((err) => this.afterPasswordSubmit(err));
    }

    public afterPasswordSubmit({errorCode, message}: any): void {
      this.logging = false;
      if (errorCode === 900) {
        this.need2fa = true;
        (this.rules.otp as any)[0].required = true;
      } else if (errorCode > 900 && errorCode <= 999) {
        this.$message.error(message);
      }
    }

    public login0(userData: LoginResponse<User>): void {
      UserUtil.set(userData);
      this.loadMenu();
    }

    public loadMenu() {
      ControlPanelApi.getMenus().then((menus) => {
        this.refreshMenus(menus);
        this.$router.addRoutes(this.routers);

        this.$router.push({
          name: 'ControlPanel_PersonalData'
        });
      });
    }

    public scanLogin(type: string, agentId: string): void {
      if (type && agentId) {
        this.$router.push({
          name: `Oauth_${type}_ScanLogin`,
          params: {
            agentId
          }
        });
      }
    }
  }
</script>
<style lang="scss" scoped>
    @import "@/assets/login.scss";
    @import "@/assets/oauth.scss";

    .oauth-box {
        width: 365px;
        border-top: 1px solid #CCCCCC;
        font-size: 14px;
        padding: 10px;
        text-align: center;

        > * {
            display: inline-block;
            vertical-align: middle;
        }
    }

    .oauth-title {
        margin-right: 12px;
    }
</style>
